package edu.stanford.prpl.app.prpltalk.android;

import java.util.List;

import edu.stanford.prpl.api.Identity;
import edu.stanford.prpl.app.prpltalk.PRPLTalk.BuddyInfo;
import edu.stanford.prpl.app.prpltalk.android.R.id;
import edu.stanford.prpl.app.prpltalk.android.R.layout;
import edu.stanford.prpl.common.util.URIUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;

public class EditContact extends Activity {

	/**
	 * Determines what the EditContact page will be editing 0 - Edit Personal Contact info 1 - Edit other current
	 * existing Contacts 2 - Add New Contact
	 */
	public static final String KEY_CONTACT_TYPE = "edit_contact_type";

	public static final int ACTIVITY_EDIT_PERSONAL_CONTACT = 0;
	public static final int ACTIVITY_EDIT_OTHER_CONTACT = 1;
	public static final int ACTIVITY_ADD_NEW_CONTACT = 2;

	/**
	 * Only used for ACTIVITY_EDIT_OTHER_CONTACT, retrieves the email of the contact being edited
	 */
	public static final String KEY_CONTACT_ID = "edit_contact_id";

	private static final String TAG = "MyActivity";

	/** Id of the session this activity is related to */
	private int editContactType;

	private String oldContactEmail;
	private EditText contactNameEdit;
	private EditText contactEmailEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_contact);
		setTitle("PrPlTalk");

		// Retrieve the contact type being edited
		this.editContactType = savedInstanceState != null ? savedInstanceState
				.getInt(EditContact.KEY_CONTACT_TYPE) : -1;
		if (this.editContactType == -1) {
			Bundle extras = getIntent().getExtras();
			this.editContactType = extras != null ? extras.getInt(EditContact.KEY_CONTACT_TYPE) : -1;
		}

		TextView editContactTitle = (TextView) findViewById(R.id.editContactTitle);
		TextView contactNameLabel = (TextView) findViewById(R.id.contactNameLabel);
		contactNameEdit = (EditText) findViewById(R.id.contactNameEdit);
		TextView contactEmailLabel = (TextView) findViewById(R.id.contactEmailLabel);
		contactEmailEdit = (EditText) findViewById(R.id.contactEmailEdit);

		TextView updateIntervalLabel1 = (TextView) findViewById(R.id.updateIntervalLabel1);
		EditText updateIntervalEdit = (EditText) findViewById(R.id.updateIntervalEdit);
		TextView updateIntervalLabel2 = (TextView) findViewById(R.id.updateIntervalLabel2);

		Button okayButton = (Button) findViewById(R.id.okBtn);
		Button cancelButton = (Button) findViewById(R.id.cancelBtn);

		updateIntervalLabel1.setVisibility(View.INVISIBLE);
		updateIntervalEdit.setVisibility(View.INVISIBLE);
		updateIntervalLabel2.setVisibility(View.INVISIBLE);

		// For personal contact, retrieve current personal data
		if (this.editContactType == EditContact.ACTIVITY_EDIT_PERSONAL_CONTACT) {
			editContactTitle.setText("Edit Your Preferences");

			Contact myContact = ContactManager.getInstance().getMyContact();
			contactNameLabel.setText("Your Contact Name: ");
			contactNameEdit.setText(myContact.getName());
			contactEmailLabel.setText("Your Contact Email Address: ");
			contactEmailEdit.setText(myContact.getEmail());

			// updateIntervalLabel1.setVisibility(View.VISIBLE);
			// updateIntervalEdit.setVisibility(View.VISIBLE);
			// updateIntervalLabel2.setVisibility(View.VISIBLE);
			// updateIntervalEdit.setText((int)ContactManager.getInstance().getUpdateInterval());
		}
		// For other contacts, populate field with contact data
		else if (this.editContactType == EditContact.ACTIVITY_EDIT_OTHER_CONTACT) {
			editContactTitle.setText("Edit Contact Information");

			// Retrieve contact email id
			this.oldContactEmail = savedInstanceState != null ? savedInstanceState
					.getString(EditContact.KEY_CONTACT_ID) : null;
			if (this.oldContactEmail == null) {
				Bundle extras = getIntent().getExtras();
				this.oldContactEmail = extras != null ? extras.getString(EditContact.KEY_CONTACT_ID) : null;
			}

			Contact editContact = ContactManager.getInstance().getContact(this.oldContactEmail);
			contactNameEdit.setText(editContact.getName());
			contactEmailEdit.setText(editContact.getEmail());
		} else {
			editContactTitle.setText("Add New Contact");

			contactNameEdit.setText("");
			contactEmailEdit.setText("");
			okayButton.setText("Add New Contact");
		}

		okayButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				String newContactName = contactNameEdit.getText().toString().trim();
				String newContactEmail = contactEmailEdit.getText().toString().trim();
				Contact myContact = ContactManager.getInstance().getMyContact();

				if (newContactName.length() == 0) {
					errorInfoBox("The contact name is empty. Please specify a contact name.");
					return;
				}
				if (newContactEmail.length() == 0) {
					errorInfoBox("The contact email is empty. Please specify a contact email.");
					return;
				}

				if (editContactType == EditContact.ACTIVITY_EDIT_PERSONAL_CONTACT) {
					// EditText updateIntervalEdit = (EditText) findViewById(R.id.updateIntervalEdit);
					// int minsUpdate = Integer.getInteger(updateIntervalEdit.getText().toString());
					// Log.d(TAG, "User specified to update contacts every "+minsUpdate+" minutes");

					// For Personal Contact, check that personal
					// email doesn't exist among other contacts
					if (ContactManager.getInstance().getContact(newContactEmail) == null)
						ContactManager.getInstance().setMyContact(newContactName, newContactEmail);
					else {
						errorInfoBox("The email '" + newContactEmail
								+ "' is currently in use for another contact. Please specify a different email.");
						return;
					}
				} else if (editContactType == EditContact.ACTIVITY_EDIT_OTHER_CONTACT) {
					// For other Contacts, check that email doesn't
					// already exist among other contacts
					if (newContactEmail.equals(myContact.getEmail())) {
						errorInfoBox("The email '"
								+ newContactEmail
								+ "' is currently used for your personal contact. Please specify a different email.");
						return;
					} else if (ContactManager.getInstance().getContact(newContactEmail) != null) {
						if (!oldContactEmail.equals(newContactEmail)) {
							errorInfoBox("The email '"
									+ newContactEmail
									+ "' is currently used in another existing contact. Please specify a different email.");
							return;
						}
					}

					ContactManager.getInstance().deleteContact(oldContactEmail);
					// Do something here to update a contact/buddy to PrPl
					String identityURI = URIUtils.getIdentityURI(oldContactEmail);				
					Identity identity = PrPlTalkActivity.prplAppClient.getIdentityManager().getIdentityByURI(
							identityURI, true);
					identity.setName(newContactName);
					// ContactManager.getInstance().addOrUpdateOnlineContact(newContactName, newContactEmail,
					// null);
				} else {
					// For other Contacts or adding new Contact, check that email doesn't
					// already exist among other contacts
					if (newContactEmail.equals(myContact.getEmail())) {
						errorInfoBox("The email '"
								+ newContactEmail
								+ "' is currently used for your personal contact. Please specify a different email.");
						return;
					} else if (ContactManager.getInstance().getContact(newContactEmail) != null) {
						errorInfoBox("The email '" + newContactEmail
								+ "' is currently used in an existing contact. Please specify a different email.");
						return;
					}

					// Do something here to add a new contact/buddy to PrPl
					String identityURI = URIUtils.getIdentityURI(newContactEmail);
					Identity identity = PrPlTalkActivity.prplAppClient.getIdentityManager().getIdentityByURI(
							identityURI, true);
					identity.setName(newContactName);
					// BuddyInfo object?
					// ContactManager.getInstance().addOrUpdateOnlineContact(BuddyInfo contactInfo, null);

				}

				// Log.d(TAG, "Send Button Clicked!");
				finish();
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				finish();
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void errorInfoBox(String errorMsg) {
		new AlertDialog.Builder(this).setTitle("Error").setMessage(errorMsg).setPositiveButton("OK",
				new OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				}).setOnCancelListener(new OnCancelListener() {
			
			public void onCancel(DialogInterface dialog) {
				return;
			}
		}).show();
	}

}
